#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("TCP - 客户端");
    //创建通信的套接字对象
    ui->ip->setText("127.0.0.1");
    m_tcp = new QTcpSocket(this);
    ui->close->setEnabled(false);
    //检测是否和服务器连接成功
    connect(m_tcp,&QTcpSocket::connected,this,[=]()
            {
                ui->rec->append("恭喜，服务器连接成功!");
                ui->m_status->setText("已连接");
            });
    //检测服务器是都恢复了数据
    connect(m_tcp,&QTcpSocket::readyRead,[=]()
            {
                QByteArray recvMsg = m_tcp->readAll();
                ui->rec->append("服务器say:"+recvMsg);
                ui->rec->setAlignment(Qt::AlignRight);
            });
    //检测服务器是否断开了连接
    connect(m_tcp,&QTcpSocket::disconnected,this,[=]()
            {
                ui->rec->append("服务器已经断开了连接");
                ui->connet->setEnabled(true);
                ui->close->setEnabled(false);
            });
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_connet_clicked()
{
    QString ip = ui->ip->text();
    unsigned short port = ui->port->text().toInt();
    //连接服务器
    m_tcp->connectToHost(ip,port);
    ui->connet->setEnabled(false);
    ui->close->setEnabled(true);
}


void MainWindow::on_close_clicked()
{
    m_tcp->close();
    ui->connet->setEnabled(true);
    ui->close->setEnabled(false);
}


void MainWindow::on_send_clicked()
{
    QString sendMsg = ui->msg->toPlainText();
    m_tcp->write(sendMsg.toUtf8());
    ui->rec->append("客户端Say:"+sendMsg);
    ui->rec->setAlignment(Qt::AlignLeft);
    ui->msg->clear();
}

